package com.ruoyi.water.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.water.domain.MeterAnalyse;
import com.ruoyi.water.service.IMeterAnalyseService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/water/meterAnalyse")
public class MeterAnalyseController extends BaseController {

    @Autowired
    private IMeterAnalyseService meterAnalyseService;

    /**
     * 计算并保存指定日期范围内的每日数据
     */
    @PostMapping("/calculateDailyData")
    public AjaxResult calculateDailyData(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                                         @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        int count = meterAnalyseService.calculateAndSaveDailyData(startDate, endDate);
        return AjaxResult.success("成功处理 " + count + " 条记录", count);
    }

    /**
     * 分析并更新指定日期范围内的计量数据
     */
    @PostMapping("/analyzeMeterData")
    public AjaxResult analyzeMeterData(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                                       @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        int count = meterAnalyseService.analyzeAndUpdateMeterData(startDate, endDate);
        return AjaxResult.success("成功分析并更新 " + count + " 条记录", count);
    }

    /**
     * 查询每日分析数据列表（兼容：单点时间精确查询 + 时间范围查询 + 多水表ID批量查询 + 水表名称查询）
     */
    @PreAuthorize("@ss.hasPermi('water:meterAnalyse:list')")
    @GetMapping("/list")
    public TableDataInfo list(
            MeterAnalyse meterAnalyse,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String meterIds,
            // 新增：接收水表名称参数
            @RequestParam(required = false) String meterName
    ) {
        startPage(); // 分页处理
        QueryWrapper<MeterAnalyse> queryWrapper = new QueryWrapper<>();

        // 多水表ID批量查询（优先处理meterIds，兼容原单个meterId查询）
        if (StringUtils.hasText(meterIds)) {
            List<Long> idList = Arrays.stream(meterIds.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            queryWrapper.in("meterId", idList);
        } else if (meterAnalyse.getMeterId() != null) {
            queryWrapper.eq("meterId", meterAnalyse.getMeterId());
        }

        // 新增：水表名称模糊查询
        if (StringUtils.hasText(meterName)) {
            queryWrapper.like("meterName", meterName);
        }

        // 时间条件兼容逻辑
        if (meterAnalyse.getAnalyseDate() != null) {
            queryWrapper.eq("analyseDate", meterAnalyse.getAnalyseDate());
        } else {
            if (startTime != null && !startTime.trim().isEmpty()) {
                queryWrapper.ge("analyseDate", startTime);
            }
            if (endTime != null && !endTime.trim().isEmpty()) {
                if (startTime != null && !startTime.trim().isEmpty() && startTime.compareTo(endTime) > 0) {
                    throw new RuntimeException("开始时间不能晚于结束时间");
                }
                queryWrapper.le("analyseDate", endTime);
            }
        }

        queryWrapper.orderByAsc("analyseDate");

        List<MeterAnalyse> list = meterAnalyseService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 导出水表分析结果列表
     */
    @PreAuthorize("@ss.hasPermi('water:meterAnalyse:export')")
    @Log(title = "水表分析结果", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MeterAnalyse meterAnalyse)
    {
        LambdaQueryWrapper<MeterAnalyse> queryWrapper = new LambdaQueryWrapper<>(meterAnalyse);
        List<MeterAnalyse> list = meterAnalyseService.list(queryWrapper);
        ExcelUtil<MeterAnalyse> util = new ExcelUtil<MeterAnalyse>(MeterAnalyse.class);
        util.exportExcel(response, list, "水表分析结果数据");
    }

    /**
     * 获取水表分析结果详细信息
     */
    @PreAuthorize("@ss.hasPermi('water:meterAnalyse:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(meterAnalyseService.getById(id));
    }

    /**
     * 新增水表分析结果
     */
    @PreAuthorize("@ss.hasPermi('water:meterAnalyse:add')")
    @Log(title = "水表分析结果", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MeterAnalyse meterAnalyse)
    {
        return toAjax(meterAnalyseService.save(meterAnalyse) ? 1 : 0);
    }

    /**
     * 修改水表分析结果
     */
    @PreAuthorize("@ss.hasPermi('water:meterAnalyse:edit')")
    @Log(title = "水表分析结果", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MeterAnalyse meterAnalyse)
    {
        return toAjax(meterAnalyseService.updateById(meterAnalyse) ? 1 : 0);
    }

    /**
     * 删除水表分析结果
     */
    @PreAuthorize("@ss.hasPermi('water:meterAnalyse:remove')")
    @Log(title = "水表分析结果", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(meterAnalyseService.removeByIds(List.of(ids)) ? ids.length : 0);
    }
}